﻿using Framework.Serializer;

namespace Framework.Common.Configs
{
    /// <summary>
    /// 通用配置文件,默认配置目录~/configs/
    /// 不支持泛型自动命名,请手动指定FileName
    /// 不允许修改内部配置约定
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class CustomConfig<T>
    {
        /// <summary>
        /// 构造器中创建配置文件名和全路径
        /// </summary>
        static CustomConfig()
        {
            ConfigFileName = typeof(T).Name + ".config";
            ConfigFileFullPath = CustomConfigRoot.ConfigRootPath + ConfigFileName;
        }

        #region config root setting
        /// <summary>
        /// 配置文件全路径
        /// </summary>
        public static string ConfigFileFullPath { get; private set; }
        /// <summary>
        /// 文件名称
        /// </summary>
        public static string ConfigFileName { get; private set; }
        /// <summary>
        /// configObject
        /// </summary>
        static T _configObject;

        #endregion

        /// <summary>
        /// 获取配置对象
        /// </summary>
        /// <returns></returns>
        public static T GetConfig()
        {
            if (!Equals(_configObject,default(T)))
                return _configObject;
            //反序列化获取配置对象
            _configObject = ExtensionXml.SFromFileXml<T>(ConfigFileFullPath);
            //加入文件更改监视
            FileHelper.WatchFile(ConfigFileFullPath, (a, b) => { _configObject = default(T); });
            //返回实体
            return _configObject;
        }

        /// <summary>
        /// 保存配置文件
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SaveConfig(T obj)
        {
            if (obj.SToFileXml(ConfigFileFullPath))
            {
                _configObject = obj;
                return true;
            }
            return false;
        }


    }



}
